package utils;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Utils {

	public static BufferedImage arrayToImage(int[][] m) {
		int w = m[0].length;
		int h = m.length;
		
		BufferedImage img = new BufferedImage(m[0].length, m.length, BufferedImage.TYPE_3BYTE_BGR);
		for (int x=0; x<w; x++) {
			for (int y=0; y<h; y++) {
				img.setRGB(x, y, ((m[y][x]<<16) | (m[y][x]<<8) | (m[y][x])));
			}
		}
		return img;
	}
	
	public static FilenameFilter filter = new FilenameFilter() {
	    public boolean accept(File dir, String name) {
	        return !name.startsWith(".");
	    }
	};
	
	public static void writeImageToFile(BufferedImage img, String fileName) {
		try {
			ImageIO.write(img, "JPG", new File(fileName));
		} catch (IOException e) {
			System.err.println("Could not write image to " + fileName +".");
			if (Constants.DEBUG) e.printStackTrace();
		}
	}
	
	static int ww=30, hw=30;
	// shows a frame with the image
	public static void showImage(final BufferedImage img, String title) {
		if (!Constants.DEBUG) return;
		
		JFrame f = new JFrame();
		f.setContentPane(new JPanel(){
			public void paint(Graphics g) {
				g.drawImage(img, 0, 0, null);
			}
		});
		f.setSize(new Dimension(img.getWidth()+50, img.getHeight()+50));
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		f.setTitle(title);
		f.setLocation(ww, hw);
		ww += img.getWidth()+100;
		if (ww>1000) {
			ww=30;
			hw+=300;
		}
		f.setVisible(true);
	}
/*	
	public static void main(String[] args) {
		BufferedImage img;
		try {
			img = ImageIO.read(new File("image5.jpg"));
			Utils.showImage(img, "test");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
*/
}
